<template>
  <div class="login-container">
	  <canvas id="canvas" style="width: 100%;height: 100%;"></canvas>
    <el-form
      ref="loginFormRef"
      :model="loginData"
      :rules="loginRules"
      class="login-form"
    >
      <div class="flex text-white items-center py-4 title">
<!--        <span class="text-2xl flex-1 text-center title">数字孪生场景基础支撑PASS底座平台</span>
		<div class="flex title" >

		</div>
		 -->
		<div class="logo"><img src="../../assets/images/logo.png" /></div>
		<div class="name"><span >数字孪生场景基础支撑PASS底座平台</span></div>
		
      </div>

      <el-form-item prop="username">
        <div class="p-2 text-white">
          <svg-icon icon-class="user" />
        </div>
        <el-input
          ref="username"
          v-model="loginData.username"
          class="flex-1"
          size="large"
          placeholder="账号"
          name="username"
        />
      </el-form-item>

      <el-tooltip
        :disabled="isCapslock === false"
        content="Caps lock is On"
        placement="right"
      >
        <el-form-item prop="password">
          <span class="p-2 text-white">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            v-model="loginData.password"
            class="flex-1"
            placeholder="密码"
            :type="passwordVisible === false ? 'password' : 'input'"
            size="large"
            name="password"
            @keyup="checkCapslock"
            @keyup.enter="handleLogin"
          />
          <span class="mr-2" @click="passwordVisible = !passwordVisible">
            <svg-icon
              :icon-class="passwordVisible === false ? 'eye' : 'eye-open'"
              class="text-white cursor-pointer"
            />
          </span>
        </el-form-item>
      </el-tooltip>

      <!-- 验证码 -->
      <el-button
        size="default"
        :loading="loading"
        type="primary"
        class="w-full"
        @click.prevent="handleLogin"
        >登录
      </el-button>

    </el-form>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { JSEncrypt } from "jsencrypt";

// 状态管理依赖
import { useUserStore } from "@/store/modules/user";

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";

const userStore = useUserStore();
const route = useRoute();
const publicKey='MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKyiOmdLfcrpepp8sbbFFDJ44NMEJUIAG9vTcD9S9YY9+H8INT804Y4W/egfdBdpm2AMbCs+rhWkETLjNqKJYdcCAwEAAQ==';

/**
 * 按钮loading
 */
const loading = ref(false);
/**
 * 是否大写锁定
 */
const isCapslock = ref(false);
/**
 * 密码是否可见
 */
const passwordVisible = ref(false);

/**
 * 登录表单引用
 */
const loginFormRef = ref(ElForm);

const loginData = ref<Object>({
  username: "administrator",
  password: "administrator",
});

const loginRules = {
  username: [{ required: true, trigger: "blur" }],
  password: [{ required: true, trigger: "blur", validator: passwordValidator }],
};

/**
 * 密码校验器
 */
function passwordValidator(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error("密码不能少于6位."));
  } else {
    callback();
  }
}

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e;
  isCapslock.value = key && key.length === 1 && key >= "A" && key <= "Z";
}

    //  加密
function encryptedData(data) {
  // 新建JSEncrypt对象
  let encryptor = new JSEncrypt();
  // 设置公钥
  encryptor.setPublicKey(publicKey);
  // 加密数据
  return encryptor.encrypt(data);
}



/**
 * 登录
 */
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login({
			username:encryptedData(loginData.value.username),
			password:encryptedData(loginData.value.password)
		})
        .then(() => {
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );

          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

onMounted(() => {
	cr();
});

const cr=()=>{
	
	
	const canvas = document.getElementById('canvas');
	const ctx = canvas.getContext('2d');
	
	const RESOLUTION = 1;
	
	let w = canvas.width = window.innerWidth * RESOLUTION;
	let h = canvas.height = window.innerHeight * RESOLUTION;
	
	const PARTICLE_COUNT = 400;
	const CONNECT_DISTANCE = w * 0.05;
	const FORCE_DISTANCE = w * 0.1;
	
	const r = (n = 1) => Math.random() * n;
	const PI = Math.PI;
	const TAU = PI * 2;
	
	let time = new Date;
	
	const lerp = (start, end, amt) => {
	  return (1-amt)*start+amt*end
	};
	
	const distance = (x1, y1, x2, y2) => {
		const a = x1 - x2;
		const b = y1 - y2;
		return Math.sqrt( a*a + b*b );
	};
	
	const angle = (cx, cy, ex, ey) => {
	  return Math.atan2(ey - cy, ex - cx);
	};
	
	const particlePrototype = () => ({
	  x: w * 0.5 + (Math.cos(r(TAU)) * r(w* 0.5)),
	  y: h * 0.5 + (Math.sin(r(TAU)) * r(h* 0.5)),
	  angle: r(TAU),
	  speed: r(0.15),
	  normalSpeed: r(0.15),
		oscAmplitudeX: r(2),
		oscSpeedX: 0.001 + r(0.008),
		oscAmplitudeY: r(2),
		oscSpeedY: 0.001 + (r(0.008)),
		connectDistance: r(CONNECT_DISTANCE),
		color: {
			r: Math.round(200 + r(55)),
			g: Math.round(150 + r(105)),
			b: Math.round(200 + r(55))
		}
	});
	
	const particles = (new Array(PARTICLE_COUNT))
	  .fill({})
	  .map(particlePrototype);
	
	const update = () => {
	  particles.forEach(p1 => {
	    p1.x += (Math.cos(p1.angle) + (Math.cos(time * p1.oscSpeedX) * p1.oscAmplitudeX)) * p1.speed;
	    p1.y += (Math.sin(p1.angle) + (Math.cos(time * p1.oscSpeedY) * p1.oscAmplitudeY)) * p1.speed;
	    
	    p1.speed = lerp(p1.speed, p1.normalSpeed * RESOLUTION, 0.1);
	    
	    if (p1.x > w || p1.x < 0) {
	      p1.angle = PI - p1.angle;
	    }
	    if (p1.y > h || p1.y < 0) {
	     	p1.angle = -p1.angle;
	    }
			
			if (r() < 0.005) 
				p1.oscAmplitudeX = r(2);
			if (r() < 0.005) 
				p1.oscSpeedX = 0.001 + (r(0.008));
			if (r() < 0.005) 
				p1.oscAmplitudeY = r(2);
			if (r() < 0.005) 
				p1.oscSpeedY = 0.001 + r(0.008);
			
			p1.x = Math.max(-0.01,Math.min(p1.x, w + 0.01));
			p1.y = Math.max(-0.01,Math.min(p1.y, h + 0.01));
	  });
	};
	
	const render = () => {
	  
		ctx.clearRect(0,0,w,h);
		
	  particles.map(p1 => {
	    particles
				.filter(p2 => {
					if (p1 == p2)
						return false;
					if (distance(p1.x, p1.y, p2.x, p2.y) > p1.connectDistance)
						return false;
					return true;
				})
				.map(p2 => {
					const dist = distance(p1.x, p1.y, p2.x, p2.y);
					p1.speed = lerp(p1.speed, p1.speed + (0.05 / p1.connectDistance * dist), 0.2);
					return {
						p1,
						p2,
						color: p1.color,
						opacity: Math.floor(100 / p1.connectDistance * (p1.connectDistance - dist)) / 100
					};
				})
				.forEach((line, i) => {
					const colorSwing = Math.sin(time * (line.p1.oscSpeedX));
					ctx.beginPath();
					ctx.globalAlpha = line.opacity;
					ctx.moveTo(line.p1.x, line.p1.y);
					ctx.lineTo(line.p2.x, line.p2.y);
					ctx.strokeStyle = `rgb(
						${Math.floor(line.color.r * colorSwing)},
						${Math.floor((line.color.g * 0.5) + ((line.color.g * 0.5) * colorSwing))},
						${line.color.b}
					)`
					ctx.lineWidth = (line.opacity * 4);
					ctx.stroke();
					ctx.closePath();
				});
	  });
	  
	};
	
	const loop = () => {
	  time = new Date;
	  update();
	  render();
	  window.requestAnimationFrame(loop);
	};
	
	loop();
	
	window.addEventListener('mousemove', e => {
	  
	  const mouseX = e.layerX * RESOLUTION;
	  const mouseY = e.layerY * RESOLUTION;
	  
	  particles.forEach(p => {
	    const dist = distance(mouseX, mouseY, p.x, p.y);
	    
	    if (dist < FORCE_DISTANCE && dist > 0) {
	      p.angle = angle(mouseX, mouseY, p.x, p.y)
	      const force = (FORCE_DISTANCE - dist) * 0.1;
	      p.speed = lerp(p.speed, force, 0.2);
	    }
	  });
		
	});
	
	window.addEventListener('resize', e => {
		w = canvas.width = window.innerWidth * RESOLUTION;
		h = canvas.height = window.innerHeight * RESOLUTION;
	});
}

</script>

<style lang="scss" scoped>
	
.title{
	-moz-user-select:none; /* Firefox私有属性 */
	-webkit-user-select:none; /* WebKit内核私有属性 */
	-ms-user-select:none; /* IE私有属性(IE10及以后) */
	-khtml-user-select:none; /* Khtml内核私有属性 */
	-o-user-select:none; /* Opera私有属性 */
	user-select:none; /* CSS3属性 */
	font-size: 20px;
	font-weight: bold;
	font-family: '微软雅黑';
	color: #ccc;
	display: flex;
	flex-direction: row;
	align-content: center;
	justify-content: center;
	align-items: center;
	>.logo{
		padding-top: 6px;
		padding-right: 5px;
		>img{
		 width: 100%;	
		}
	}
	>.name{
		>span{
			background-image: linear-gradient(red, blue);-webkit-background-clip: text;
			background-image:-webkit-linear-gradient(bottom,#212332,#ffffff,#ffffff);
			-webkit-background-clip:text;
			-webkit-text-fill-color:transparent;
		}
	}
}

:deep(.el-form-item--default .el-form-item__content){
	line-height: 20px;
}
	
.login-container {
	-moz-user-select:none; /* Firefox私有属性 */
	-webkit-user-select:none; /* WebKit内核私有属性 */
	-ms-user-select:none; /* IE私有属性(IE10及以后) */
	-khtml-user-select:none; /* Khtml内核私有属性 */
	-o-user-select:none; /* Opera私有属性 */
	user-select:none; /* CSS3属性 */
  width: 100%;
  min-height: 100%;
  overflow: hidden;
  background-color: #212332;

  .login-form {
    max-width: 100%;
    padding: 35px 35px 0;
    margin: 0 auto;
    overflow: hidden;
		
	width: 440px;
	height: 340px;
	position: absolute;
	background: #2a2d3e;
	border-top: 2px solid #3fa3ff;
	top: 50%;
    left: 50%;
	transform: translateX(-50%) translateY(-50%);
    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      img {
        width: 120px;
        height: 48px;
        cursor: pointer;
      }
    }
  }
}

.el-form-item {
  background: rgb(0 0 0 / 10%);
  border: 1px solid rgb(255 255 255 / 10%);
  border-radius: 5px;
}

.el-input {
  background: transparent;

  // 子组件 scoped 无效，使用 :deep
  :deep(.el-input__wrapper) {
    padding: 0;
    background: transparent;
    box-shadow: none;

    .el-input__inner {
      color: #fff;
      background: transparent;
      border: 0;
      border-radius: 0;
      caret-color: #fff;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px transparent inset !important;
        -webkit-text-fill-color: #fff !important;
      }

      // 设置输入框自动填充的延迟属性
      &:-webkit-autofill,
      &:-webkit-autofill:hover,
      &:-webkit-autofill:focus,
      &:-webkit-autofill:active {
        transition: color 99999s ease-out, background-color 99999s ease-out;
        transition-delay: 99999s;
      }
    }
  }
}
</style>
